# image_app/views.py
import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from utils import colorutils


@csrf_exempt
@require_POST
def process_image(request):
    """
    GET接口：处理图片
    参数：
    - image_url: 图片URL地址
    - target_category: 目标分类（贴图、产品图、效果图）
    """
    # 获取参数
    # 读取 request.body（字节类型）
    raw_data = request.body  # 例如 b'{"image_url": "https://example.com/image.jpg", "target_category": "产品图"}'
    # 解码为字符串
    data_str = raw_data.decode('utf-8')  # 例如 '{"image_url": "https://example.com/image.jpg", "target_category": "产品图"}'
    # 解析为 JSON
    data = json.loads(data_str)
    image_url = data.get("image_url")
    target_category = data.get("target_category")

    # 参数校验
    if not image_url or not target_category:
        return JsonResponse({
            "status": "error",
            "message": "Missing required parameters: image_url and target_category are required."
        }, status=400)

    # 调用处理函数
    result = colorutils.handle(image_url, target_category)
    return JsonResponse({"success": "true"})
